package com.shanjupay.merchant.common.intercept;

import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.domain.ErrorCode;
import com.shanjupay.common.domain.RestErrorCode;
import feign.FeignException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO
 *
 * @Description
 * @Author zhangbing
 * @Date 2024/5/13 9:01
 **/
@ControllerAdvice //与@ExceptionHandler配合使用实现全局异常处理
public class GlobalExceptionHandler {
    private static final Logger LOGGER= LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //捕获异常
    @ExceptionHandler(value=Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorCode processExcetion(HttpServletRequest request,
                                         HttpServletResponse response,Exception e){
        //解析异常信息
        //如果是系统自定义异常，直接取出errorCode和 errMessage
        if(e instanceof BusinessException){
            LOGGER.info(e.getMessage());
            //解析系统自定义异常信息
            BusinessException businessException=(BusinessException) e;
            ErrorCode errorCode = businessException.getErrorCode();
            //错误码
            int code = errorCode.getCode();
            //错误信息
            String desc = errorCode.getDesc();
            return new RestErrorCode(String.valueOf(code),desc);
        }

        //未知错误 。。。。 统一 999999系统未知错误
        LOGGER.error("系统异常",e);
        return new RestErrorCode(String.valueOf(CommonErrorCode.UNKNOWN.getCode()),CommonErrorCode.UNKNOWN.getDesc());
    }
}
